package com.qcc.cashier.react;

import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReadableMap;
import com.qcc.cashier.utils.MapUtils;
import com.qcc.cashier.utils.ObjectUtils;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.disposables.Disposable;


public class ReactUtils {
    public static <T> T mapToObject(ReadableMap map, Class<T> clazz) {
        return MapUtils.toObject(map.toHashMap(), clazz);
    }

    public static Object toReactData(Object obj) {
        if (ObjectUtils.isPrimitiveType(obj)) return obj;
        Object value = ObjectUtils.toBeanObject(obj);
        if (value instanceof List) {
            return Arguments.makeNativeArray(((List) value).toArray());
        } else if (value instanceof Arrays) return Arguments.makeNativeArray(value);
        Map map = (Map) value;
        return Arguments.makeNativeMap(map);

    }

    public static <T> void subscribe(Observable<T> observable, Promise promise) {
        subscribe(observable, promise, "500");
    }

    @SuppressWarnings({"unchecked"})
    public static <T> void subscribe(Observable<T> observable, Promise promise, String errorCode) {
        Disposable disposable = observable.subscribe(obj -> {
                    Object data = toReactData(obj);
                    promise.resolve(data);
                }
                , err -> {
                    if (err instanceof ReactException) {
                        ReactException resultException = (ReactException) err;
                        promise.reject(resultException.getCode(), resultException.getMessage(), err);
                    } else {
                        promise.reject(errorCode, err);
                    }

                });


    }


}

